<style lang="less">
@import '../../assets/css/table.less';
</style>
<template>
  <div>
    <Row :gutter="10">
      <Col>
      <Card>
        <div class="live_wrapper">
          <Input v-model="filter.name"
                 @on-search="search"
                 search
                 enter-button="搜索"
                 placeholder="请输入姓名"
                 style="display:inline-table; width: 210px;" />
          <Input v-model="filter.username"
                 @on-search="search"
                 search
                 enter-button="搜索"
                 placeholder="请输入账号"
                 style="display:inline-table; width: 210px; margin-left:10px" />
          <Select v-model="filter.role"
                  style="width:200px; margin-left:10px"
                  @on-change="search()"
                  placeholder="请选择角色">
            <Option value="">全部</Option>
            <Option v-for="(item, key) in role_list"
                    :value="item.name"
                    :key="key"
                    v-if="item.name != '超级管理员'">{{ item.name }}</Option>
          </Select>
          <Select v-model="filter.status"
                  style="width:200px; margin-left:10px"
                  @on-change="search()"
                  placeholder="请选择状态">
            <Option value="-1">全部</Option>
            <Option value="0">停用</Option>
            <Option value="1">启用</Option>
          </Select>
          <Button type="primary"
                  style="float:right;width: 90px;height: 34px;font-size: 14px;margin-left:10px"
                  @click="addManager"
                  v-if="permissionList.indexOf('user-add') !== -1">
            添加账号
          </Button>
        </div>
        <p class="admin_title">
          账号列表
        </p>
        <Row class="margin-top-10 table_pattern">
          <Table style="width: calc(100vw - 256px - 36px - 32px)"
                 :loading="loading"
                 :columns="columns"
                 :data="list"></Table>
        </Row>
        <Row class="margin-top-10">
          <Page :total="pagenation.totalPage"
                :page-size="pagenation.perPage"
                :current="pagenation.currentPage"
                show-elevator
                show-total
                @on-change="change"></Page>
        </Row>
      </Card>
      </Col>
    </Row>
    <Modal v-model="manage_create"
           :title="formValidate.id==0 ? '添加账号' : '编辑账号'"
           width="40%"
           class="public_modal_header edit_modal"
           :mask-closable="false">
      <Form :model="formValidate"
            ref="formValidate"
            :label-width="80"
            style="width: 80%;margin: 0 auto;padding-top: 28px;">
        <FormItem label="姓名"
                  prop="name"
                  class="form_red_label">
          <Input v-model="formValidate.name"
                 placeholder="请输入用户姓名" />
        </FormItem>
        <FormItem label="账号"
                  prop="username"
                  class="form_red_label">
          <Input v-model="formValidate.username"
                 placeholder="请输入用户账号，用于登录后台" />
        </FormItem>
        <FormItem label="密码"
                  prop="password"
                  class="form_red_label">
          <Input v-model="formValidate.password"
                 placeholder="请输入密码" />
        </FormItem>
        <FormItem label="头像"
                  prop="icon"
                  class="form_red_label">
          <div>
            <Row type="flex"
                 justify="start"
                 align="middle"
                 class="height-100">
              <div style="display: block;text-align: center;">
                <Upload ref="upload"
                        :max-size="1024"
                        :show-upload-list="false"
                        action="https://up.qiniup.com"
                        :on-format-error="handleFormatError"
                        :before-upload="handleBeforeUpload"
                        :on-progress="handleProgress"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :format="['jpg', 'jpeg', 'png']"
                        :data="{token:upload_token}">
                  <Button icon="ios-cloud-upload-outline">上传文件</Button>
                  <span style="padding-left:20px; color:#999">建议尺寸: 160*160px，JPG、PNG格式，图片不超过1M</span>
                </Upload>
              </div>
            </Row>
            <Row class="margin-top-20">
              <div class=""
                   v-if="this.formValidate.icon">
                <template>
                  <div class="demo-upload-list">
                    <img :src="this.formValidate.icon"
                         style='width:100px; height:100px'>
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline"
                            @click.native="handleView(this.formValidate.icon)"></Icon>
                      <Icon type="ios-trash-outline"
                            @click.native="handleRemove()"></Icon>
                    </div>
                  </div>
                </template>
              </div>
            </Row>
          </div>
        </FormItem>
        <FormItem label="角色"
                  class="form_red_label"
                  prop="role">
          <Select v-model="formValidate.role"
                  style="width:200px"
                  @on-change="selectRole">
            <Option v-for="(item, key) in role_list"
                    :value="item.name"
                    :key="key"
                    v-if="item.name != '超级管理员'">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="门店" class="form_red_label"
                  prop="shop_id" v-if="['门店人员'].includes(role)">
          <Select v-model="formValidate.shop_id"
                  filterable
                  style="width:200px">
            <Option v-for="(item, key) in shop_list"
                    :value="item.id"
                    :key="key">{{ item.name }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div class="btns">
        <Button :loading="saving"
                type="primary"
                @click="handleSubmit('formValidate')"
                style="margin-left:20px">提交</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { childBtnPermission, getQiniu, getUserList, editeUser, changeUserStatus, roleList, shopForSelect } from '@/api/main'
import User from '@/model/User'
export default {
  data () {
    return {
      shop_list: [],
      permissionList: [],
      brand_logo: '',
      upload_token: '',
      qiniu_url: '',
      visible: false,
      filter: {
        page: 0,
        keyword: '',
        shop_name: '',
        status: '-2',
        role: ''
      },
      list: [],
      shop_id_list: [],
      loading: true,
      saving: false,
      manage_create: false,
      pagenation: {},
      role_list: [],
      formValidate: {
        id: 0,
        shop_id: 0,
        name: '',
        username: '',
        password: '',
        icon: '',
        role: '',
      },
      columns: [
        {
          key: 'name',
          title: '姓名',
          render: (h, params) => {
            return h('strong', params.row.name)
          },
        },
        {
          key: 'username',
          title: '账号',
          render: (h, params) => {
            return h('strong', params.row.username)
          },
        },
        {
          key: 'role',
          title: '角色',
          render: (h, params) => {
            return h('strong', params.row.role)
          },
        },
        {
          key: 'shop_name',
          title: '门店',
          render: (h, params) => {
            return h('strong', params.row.shop_name)
          },
        },
        {
          key: 'status',
          title: '状态',
          align: 'center',
          render: (h, params) => h('i-switch', {
            props: {
              value: params.row.status,
              'true-value': 1,
              'false-value': 0
            },
            style: {
              width: '60px'
            },
            on: {
              'on-change': () => {
                let obj = {}
                obj.id = params.row.id
                obj.status = params.row.status ? 0 : 1
                this.changeUserStatus(obj)
              }
            }
          }, [
            h('span', {
              slot: 'open',
              domProps: {
                innerHTML: '启用'
              }
            }),
            h('span', {
              slot: 'close',
              domProps: {
                innerHTML: '禁用'
              }
            })
          ]
          )
        },
        /*{
          key: 'new_login_time',
          title: '最新登录时间',
          render: (h, params) => {
            return h('strong', params.row.new_login_time)
          },
        },
        {
          key: 'ip_address',
          title: '登录地址',
          render: (h, params) => {
            return h('strong', params.row.ip_address)
          },
        },*/
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                  },
                  style: {
                    marginRight: '5px',
                    border: 0,
                    background: 'transparent',
                    fontSize: '14px',
                    color: '#377EEF',
                    display: (this.permissionList.indexOf('user-edit') !== -1) ? 'inline-block' : 'none'
                  },
                  on: {
                    click: () => {
                      //console.log(params.row)
                      this.showManageForm(params.row)
                    },
                  },
                },
                '编辑',
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除该账号吗?',
                    transfer: true,
                  },
                  on: {
                    'on-ok': () => {
                      let obj = {}
                      obj.id = params.row.id
                      obj.status = -1
                      this.changeUserStatus(obj)
                    },
                  },
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        margin: '0 5px 0 0',
                        border: 0,
                        background: 'transparent',
                        fontSize: '14px',
                        color: '#D40303',
                        display: this.permissionList.indexOf('user-delete') !== -1 ? 'inline-block' : 'none'
                      },
                      props: {
                        type: 'error',
                        placement: 'top',
                        size: 'small',
                      },
                    },
                    '删除',
                  ),
                ],
              ),
            ])
          },
        },
      ],
      role: '',
      user: {},
    }
  },
  methods: {
    selectRole (value) {
      this.role = value
      console.log(this.role )
    },
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getUserList()
    },
    search () {
      this.filter.page = 0
      this.getUserList()
    },
    addManager: function () {
      this.manage_create = true
      this.uid = 0
      this.formValidate.id = 0
      this.handleReset('formValidate')
      this.formValidate.shop_id = this.user.shop_id
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    showManageForm (obj) {
      this.uid = obj.id
      this.manage_create = true
      this.formValidate = Object.assign({}, obj)
    },
    handleSubmit () {
      let _this = this
      if (_this.formValidate.name == '' || _this.formValidate.name.length < 2) {
        _this.$Message.error('请输入姓名,字数不少于2个字'); return;
      }
      if (_this.formValidate.username == '') {
        _this.$Message.error('请输入账号'); return;
      }
      if (_this.formValidate.password == '') {
        _this.$Message.error('请输入密码'); return;
      }
      if (_this.formValidate.icon == '') {
        _this.$Message.error('请上传头像'); return;
      }
      if (_this.formValidate.role == '') {
        _this.$Message.error('请配置角色'); return;
      }
      if (['门店人员'].includes(_this.role) && !_this.formValidate.shop_id) {
        _this.$Message.error('请选择门店'); return;
      }
      editeUser(this.formValidate).then(res => {
        if (res.code === 0) {
          _this.$Message.success('操作成功')
          _this.saving = false
          _this.manage_create = false
          _this.getUserList()
        } else {
          _this.$Message.error(res.text)
        }
      })
    },
    changeUserStatus: function (obj) {
      changeUserStatus(obj).then(res => {
        if (res.code === 0) {
          this.$Message.success("操作成功");
          this.getUserList()
        }
      })
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleBeforeUpload (file) {
      if (file.size > 1024 * 1024) {
        this.$Message.error("图片不超过1M");
        return;
      }
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.formValidate.icon = file.response.domain + file.response.key
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove () {
      this.formValidate.icon = '';
    },
    async init () {
      let _this = this
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
      this.qiniu_url = qiniu.url
    },
    getUserList () {
      getUserList(this.filter).then(res => {
        if (res.code === 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
          this.brand_logo = res.brand_logo
        } else {
          this.loading = false
          this.$Message.error(res.text)
        }
      })
    }
  },
  mounted () {
    this.init()
    roleList().then(res => {
      if (res.code === 0) {
        this.role_list = res.data
      }
    })
    childBtnPermission({ parent_name: 'user-list' }).then(res => {
      if (res.code == 0) {
        this.permissionList = res.data
      }
    })
    shopForSelect().then(res => {
      if (res.code === 0) {
        this.shop_list = res.data
      }
    })
    this.getUserList()
    this.user = JSON.parse(localStorage.getItem('user_admin'))
  },
}
</script>
<style lang="less" scoped>
.form_red_label {
	position: relative;
	&:before {
		content: '*';
		font-size: 20px;
		color: #ff4c53;
		border-radius: 50%;
		position: absolute;
		top: 4px;
		left: 37px;
		display: block;
	}
}
</style>
<style lang="less">
.demo-upload-list {
	display: inline-block;
	text-align: center;
	border-radius: 4px;
	overflow: hidden;
	background: #fff;
	position: relative;
}

.demo-upload-list img {
	width: 100%;
	height: 100%;
}

.demo-upload-list-cover {
	display: none;
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(0, 0, 0, 0.6);
}

.demo-upload-list:hover .demo-upload-list-cover {
	display: block;
}

.demo-upload-list-cover i {
	color: #fff;
	font-size: 20px;
	cursor: pointer;
	margin: 40px 6px;
}

p.prompt {
	color: #dddee1;
}

.btn_right {
	width: 1%;
	margin-left: -25px;
}

.special_check {
	width: 22%;
	height: 30px;
	margin-left: 10px;
	display: inline-block;
	padding-left: 1%;
}

#subscription_info {
	div {
		display: flex;
		justify-content: space-between;
		font-size: 15px;
		margin-top: 10px;
		flex-wrap: wrap;

		label {
			width: 30%;
		}
		span {
			width: 60%;
			word-wrap: break-word;
			text-align: right;
		}
	}
}
</style>
